import { Injectable, NotFoundException, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Coupon } from './coupon.entity';
import { CreateCouponDto } from './dto/create-coupon.dto';
import { UpdateCouponDto } from './dto/update-coupon.dto';
import { Cron, CronExpression } from '@nestjs/schedule';

@Injectable()
export class MarketingService {
  private readonly logger = new Logger('CouponSchedule');

  constructor(
    @InjectRepository(Coupon)
    private readonly couponRepository: Repository<Coupon>,
  ) {}

  async create(dto: CreateCouponDto): Promise<Coupon> {
    const coupon = this.couponRepository.create(dto);
    return this.couponRepository.save(coupon);
  }

  async findAll(): Promise<Coupon[]> {
    return this.couponRepository.find();
  }

  async findOne(id: number): Promise<Coupon> {
    const coupon = await this.couponRepository.findOne({ where: { id } });
    if (!coupon) throw new NotFoundException('优惠券不存在');
    return coupon;
  }

  async update(id: number, dto: UpdateCouponDto): Promise<Coupon> {
    const coupon = await this.findOne(id);
    Object.assign(coupon, dto);
    return this.couponRepository.save(coupon);
  }

  async remove(id: number): Promise<void> {
    await this.couponRepository.delete(id);
  }

  @Cron(CronExpression.EVERY_DAY_AT_MIDNIGHT)
  async expireCoupons() {
    const now = new Date();
    const result = await this.couponRepository.createQueryBuilder()
      .update()
      .set({ status: 'expired' })
      .where('validTo < :now AND status = :status', { now, status: 'active' })
      .execute();
    if (result.affected) {
      this.logger.log(`自动过期优惠券数量: ${result.affected}`);
    }
  }
}
